package br.com.dev.tcc.adapter;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import br.com.dev.tcc.R;
import br.com.dev.tcc.bean.Apolice;
import br.com.dev.tcc.bean.Lembrete;
import br.com.dev.tcc.database.DatabaseHelper;
import br.com.dev.tcc.database.dao.ApoliceDAO;
import br.com.dev.tcc.util.IpvaUtil;
import br.com.dev.tcc.util.RodizioUtil;
import br.com.dev.tcc.util.alarm.ApolicesAlarmManager;

public class ListaApolicesLembretesAdapter extends BaseAdapter {

	private Context ctx;
	private LayoutInflater inflater;
	private List<Apolice> itens;
	private OnAlarmModifiedListener listener;

	public ListaApolicesLembretesAdapter(Context ctx, List<Apolice> itens,
			OnAlarmModifiedListener listener) {

		inflater = LayoutInflater.from(ctx);
		this.itens = itens;
		this.ctx = ctx;
		this.listener = listener;
	}

	public void setListener(OnAlarmModifiedListener listener) {
		this.listener = listener;
	}

	@Override
	public int getCount() {

		return itens.size();
	}

	@Override
	public Object getItem(int pos) {

		return itens.get(pos);
	}

	@Override
	public long getItemId(int pos) {

		return pos;
	}

	@Override
	public View getView(int pos, View view, ViewGroup vg) {

		final Apolice apolice = itens.get(pos);

		view = inflater.inflate(R.layout.prefs_apolice, null);

		TextView tvValueApolice = (TextView) view
				.findViewById(R.id.tvValueApolice);
		TextView tvValueLicenca = (TextView) view
				.findViewById(R.id.tvValueLicenca);
		TextView tvValueIpva = (TextView) view
				.findViewById(R.id.tvValueIPVA);
		TextView tvValueRodizio = (TextView) view
				.findViewById(R.id.tvValueRodizio);		
		CheckBox checkAlarmes = (CheckBox) view.findViewById(R.id.checkAlarmes);

		tvValueApolice.setText(apolice.getHash());
		tvValueLicenca.setText(getDiasRestantes(apolice.getVencimento()));
		tvValueRodizio.setText(getLembreteRodizio(apolice));
		tvValueIpva.setText(getDiasRestantes(getLembreteIpva(apolice).getDate()));

		checkAlarmes.setChecked(hasAlarme(apolice));

		checkAlarmes.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton c, boolean checked) {

				if (checked) {
					Lembrete lembrete = new Lembrete();
					lembrete.setDate(apolice.getVencimento());
					apolice.setLembreteLicenca(lembrete);
					lembrete = getLembreteIpva(apolice);
					apolice.setLembreteIpva(lembrete);
					lembrete = new Lembrete();
					lembrete.setDate(RodizioUtil.getDatetimeRodizio(apolice.getVeiculo().getPlaca()));
					apolice.setLembreteRodizio(lembrete);
				} 
				else {

					apolice.setLembreteLicenca(new Lembrete());
					apolice.setLembreteIpva(new Lembrete());
					apolice.setLembreteRodizio(new Lembrete());
				}

				atualizaLembretes(apolice);
			}
		});

		OnClickListener clickListener = new OnClickListener() {

			@Override
			public void onClick(View view) {

				view.startAnimation(AnimationUtils.loadAnimation(ctx,
						R.anim.scale_accelerate));
			}
		};

		checkAlarmes.setOnClickListener(clickListener);

		return view;
	}

	private boolean hasAlarme(Apolice apolice) {

		return (apolice.getLembreteLicenca() != null
				&& apolice.getLembreteLicenca().getDate() != null)
				|| (apolice.getLembreteIpva() != null
				&& apolice.getLembreteIpva().getDate() != null)
				|| (apolice.getLembreteRodizio() != null
				&& apolice.getLembreteRodizio().getDate() != null);
	}

	private Lembrete getLembreteIpva(Apolice apolice) {
		
		Lembrete lembrete = new Lembrete();
		
		Calendar c = Calendar.getInstance();
		if(c.get(Calendar.MONTH) == 3)
			return lembrete;
		
		String placa = apolice.getVeiculo().getPlaca();
		lembrete.setDate(IpvaUtil.getCalendarIpva(placa));
		
		return lembrete;
	}
	
	private String getLembreteRodizio(Apolice apolice) {
		
		return RodizioUtil.getDiaRodizio(ctx, apolice.getVeiculo().getPlaca());
	}
	
	private void atualizaLembretes(final Apolice apolice) {

		listener.onModify();

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {

				DatabaseHelper dbh = new DatabaseHelper(ctx);
				ApoliceDAO dao = new ApoliceDAO(dbh);
				dao.salvaLembretes(apolice);

				ApolicesAlarmManager.buildAlarms(ctx);

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {

				listener.onFinishModify();
			}
		}.execute();
	}

	private String getDiasRestantes(Calendar data) {

		if(data == null)
			return ctx.getResources().getString(R.string.indisponivel);
			
		String diasRestantes = "";

		Calendar hoje = Calendar.getInstance();

		long diferenca = data.getTimeInMillis() - hoje.getTimeInMillis();

		int tempoDia = 1000 * 60 * 60 * 24;

		double dias = (double) diferenca / (double) tempoDia;

		if (dias >= 0) {

			BigDecimal dif = new BigDecimal(diferenca);
			dif = dif.divide(new BigDecimal(tempoDia), BigDecimal.ROUND_UP);

			diasRestantes = ctx.getResources().getString(
					R.string.dias_restantes);
			diasRestantes = diasRestantes.replace("?",
					Integer.toString(dif.intValue()));
		} else if (dias > -1) {
			diasRestantes = ctx.getResources().getString(
					R.string.dias_restantes);
			diasRestantes = diasRestantes.replace("?", "0");
		} else {
			diasRestantes = ctx.getResources().getString(R.string.dias_atras);
			diasRestantes = diasRestantes.replace("?",
					Integer.toString((int) Math.abs(dias)));
		}

		return diasRestantes;
	}

	public interface OnAlarmModifiedListener {

		void onModify();

		void onFinishModify();
	}
}
